<?php

namespace App\Http\Services;

use App\Http\Model\Hint;
use App\Http\Model\UserAnchor;
use Illuminate\Support\Facades\Redis;

/**
 * 锚点 - 用户分享
 */
class UserAnchorServices extends CommonServices
{
    protected $modelUserAnchor;

    public function __construct()
    {
        parent::__construct();

        $this->modelUserAnchor = new UserAnchor();
    }


    /**
     * @param string $index 记录类型
     * @return array|string
     */
    public function getActionType($index='')
    {
        $data = $this->modelUserAnchor -> getActionType();
        if ($index){
            $data = (array)$data[$index];
        }
        return $data;
    }



    /**
     * 添加锚点
     */
    public function addLog(array $data)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        try {
            if (empty($data['action_type'])){
                throw new \Exception("action_type 参数不能是空");
            }
            $action = $this -> getActionType();
            $type = array_keys($action);
            if (empty($type)){
                throw new \Exception("action_type 类型未配置");
            }
            if (!in_array($data['action_type'], $type)){
                throw new \Exception("action_type 类型暂不支持");
            }

            $userId = (int)$data['user_id'];
            if ($userId<=0){
                throw new \Exception('用户未登录');
            }

            $inster = [];
            $inster['user_id'] = $userId;
            $inster['to_user_id'] = (int)$data['to_user_id'];
            $inster['action_type'] = $data['action_type'];
            $inster['source'] = (string)$data['source'];
            $inster['target'] = (string)$data['target'];
            $inster['value'] = (int)$data['value'];
            $inster['add_time'] = time();
            $inster['remarks'] = $data['remarks'] ? addslashes($data['remarks']) : '';
            $res = $this->modelUserAnchor -> add($inster);
            if (!$res){
                throw new \Exception("记录数据处理异常");
            }

        } catch (\Exception $e) {
            $code = Hint::ERROR;
            $msg = $e->getMessage();
        }

        return compact('code', 'msg', 'data');

    }

}